package com.leetcode.tree.recursion;

import com.leetcode.basic.TreeNode;

/**
 * @author Dennis Li
 * @date 2020/6/15 16:58
 */
public class MergeTrees_617 {
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        // 合并的递归终止条件
        if (t1 == null && t2 == null) return null;
        if (t1 == null) return t2;
        if (t2 == null) return t1;
        // 当前结点的值是两个结点值相加
        TreeNode node = new TreeNode(t1.val + t2.val);
        // 树的合并是一一对应合并的
        node.left = mergeTrees(t1.left, t2.left);
        node.right = mergeTrees(t1.right, t2.right);
        return node;
    }

    static class Solution {
        public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
            if (t1 == null && t2 == null) return null;
            if (t1 == null) return t2;
            if (t2 == null) return t1;
            TreeNode node = new TreeNode(t1.val + t2.val);
            node.left = mergeTrees(t1.left, t2.left);
            node.right = mergeTrees(t1.right, t2.right);
            return node;
        }
    }

}
